<template>
  <div class="app-container custom-order-page">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="批生产指令编号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入批生产指令编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="指令状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择指令状态" clearable>
          <el-option v-for="dict in dict.type.order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="派单状态" prop="productionStatus">
        <el-select v-model="queryParams.productionStatus" placeholder="请选择派单状态" clearable>
          <el-option v-for="dict in dict.type.production_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['product:order:edit']">复核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['product:order:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 主表格（只保留这一个表格） -->
    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange" stripe border
      class="custom-table">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="生产指令编号" align="center" prop="orderCode" />
      <el-table-column label="指令名称" align="center" prop="orderName" />
      <el-table-column label="所属产业类型" align="center" prop="gmpIndustry" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品批号" align="center" prop="productCode" />
      <el-table-column label="物料批号" align="center" prop="productionMaterialCode" />
      <el-table-column label="产品规格" align="center" prop="spec" />
      <el-table-column label="计划产量" align="center" prop="plannedOutput" />
      <el-table-column label="车间编码" align="center" prop="roomCode" />
      <el-table-column label="批准人" align="center" prop="approver" />
      <el-table-column label="批准日期" align="center" prop="approveDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="生产内容" align="center" width="160">
        <template slot-scope="scope">
          <a v-if="scope.row.contentUrl" :href="scope.row.contentUrl" target="_blank"
            :download="getFileName(scope.row.contentUrl)" class="download-link">
            <i class="el-icon-download" style="margin-right: 4px;"></i> 下载
          </a>
          <span v-else class="no-file">无文件</span>
        </template>
      </el-table-column>

      <el-table-column label="指令备注" align="center">
        <template slot-scope="scope">
          <div v-html="scope.row.remark"></div>
        </template>
      </el-table-column>
      <el-table-column label="指令状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.orderStatus" />
        </template>
      </el-table-column>

      <el-table-column label="派单状态" align="center" prop="productionStatus" width="180">
        <template slot-scope="scope">
          <div class="production-status-btn" :class="getStatusClass(scope.row.productionStatus)"
            @click="handleStatusClick(scope.row)">
            <i class="status-icon" :class="getStatusIcon(scope.row.productionStatus)"></i>
            <span class="status-text">
              {{ getStatusText(scope.row.productionStatus) }}
            </span>
            <span class="action-hint" v-if="scope.row.productionStatus === 0">
              <i class="el-icon-angle-right"></i>
            </span>
            <span class="action-hint" v-if="scope.row.productionStatus === 4">
              <i class="el-icon-angle-right"></i>
            </span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="派单编码" align="center" prop="workOrderCode" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['product:order:edit']">复核</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['product:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" class="custom-pagination" />

    <!-- 添加或修改生产指令对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body class="custom-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="custom-dialog-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="指令名称" prop="orderName">
              <el-input v-model="form.orderName" placeholder="请输入指令名称" class="custom-input" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属产业类型" prop="gmpIndustry">
              <el-select v-model="form.gmpIndustry" placeholder="请选择所属产业类型" class="custom-select" :disabled="true">
                <el-option label="生物医药" value="生物医药" />
                <el-option label="食品" value="食品" />
                <el-option label="医疗器械" value="医疗器械" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" class="custom-input" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品规格" prop="spec">
              <el-input v-model="form.spec" placeholder="请输入产品规格" class="custom-input" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="物料需求表" prop="productionMaterialCode">
          <el-button type="primary" @click="showMaterialSelectDialog" class="custom-btn">查看物料需求表</el-button>
          <material-select-dialog @material-selected="handleMaterialSelected" @dialog-closed="dialogClosed"
            ref="materialSelectDialog" />
          <div v-if="form.productionMaterialCode" class="material-info custom-material-info">
            已选物料编码：{{ form.productionMaterialCode }}
          </div>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划产量" prop="plannedOutput">
              <el-input v-model="form.plannedOutput" placeholder="请输入计划产量" class="custom-input" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车间编码" prop="roomCode">
              <el-select v-model="form.roomCode" placeholder="请选择车间编码" class="custom-select" :disabled="true">
                <el-option v-for="room in formattedRooms" :key="room.roomCode" :label="room.roomName"
                  :value="room.roomCode" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="批准人" prop="approver">
              <el-input v-model="form.approver" placeholder="请输入批准人" class="custom-input" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批准日期" prop="approveDate">
              <el-date-picker clearable v-model="form.approveDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择批准日期" class="custom-date-picker" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="生产内容文件" prop="contentUrl">
          <file-upload v-model="form.contentUrl" :action="'common/upload'" :data="{ bucketName: bucketName }"
            :multiple="false" :limit="1" :fileSize="10" :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'txt']"
            class="custom-file-upload" :disabled="true" />
        </el-form-item>
        <el-form-item label="指令备注">
          <editor v-model="form.remark" :min-height="192" class="custom-editor" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="指令状态" prop="orderStatus">
              <el-select v-model="form.orderStatus" placeholder="请选择指令状态" class="custom-select">
                <el-option v-for="dict in dict.type.order_status" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer custom-dialog-footer">
        <el-button @click="cancel" class="custom-btn">取 消</el-button>
        <el-button type="primary" @click="submitForm" class="custom-btn">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 派单组件 -->
    <dispatch-dialog :visible.sync="dispatchVisible" :order-code="selectedOrderCode" @dispatchSuccess="getList" />

    <!-- 查看派单弹窗（异常状态）- 已修复变量名 -->
    <el-dialog title="查看派单信息（异常）" :visible.sync="viewDispatchVisible" width="700px" append-to-body
      class="custom-dialog">
      <!-- 修复：传递正确的变量名 viewOrderCode -->
      <dispatch-view :order-code="viewOrderCode" />
      <div slot="footer" class="dialog-footer custom-dialog-footer">
        <el-button @click="viewDispatchVisible = false" class="custom-btn">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listOrder, getOrder, addOrder, updateOrder } from "@/api/product/order"
import { findAllRoomsinformation } from "@/api/rooms/roomsinformation"
import MaterialSelectDialog from "./MaterialSelectDialog.vue";
import FileUpload from "@/components/FileUpload/index.vue"
import DispatchDialog from "./DispatchDialog.vue";
import DispatchView from "./DispatchView.vue";

export default {
  name: "Order",
  components: {
    MaterialSelectDialog,
    FileUpload,
    DispatchDialog,
    DispatchView // 已注册
  },
  dicts: ['order_status', 'production_status'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      orderList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        orderStatus: null,
        productionStatus: null,
      },
      form: {
        productionMaterialCode: "",
        selectedMaterials: [],
      },
      rules: {},
      rooms: [],
      formattedRooms: [],
      bucketName: "production-order",
      dispatchVisible: false,
      selectedOrderCode: "",
      // 修复：变量名统一为 viewOrderCode（避免和其他变量冲突）
      viewDispatchVisible: false,
      viewOrderCode: "" // 关键修复：之前误写为 OrderCode（大写O），现在改为 viewOrderCode
    }
  },
  created() {
    this.getList();
    this.getRooms();
  },
  methods: {
    getStatusText(status) {
      const statusStr = String(status);
      const statusMap = {
        '0': '未派单',
        '1': '待接单',
        '2': '已接单',
        '3': '已完成',
        '4': '有异常'
      };
      return statusMap[statusStr] || '未知状态';
    },

    getStatusIcon(status) {
      const iconMap = {
        '0': 'el-icon-circle-plus-outline',
        '1': 'el-icon-time',
        '2': 'el-icon-check-circle-outline',
        '3': 'el-icon-success',
        '4': 'el-icon-warning-outline'
      };
      return iconMap[status] || 'el-icon-question';
    },

    getStatusClass(status) {
      // 修复：注释单独一行，避免干扰样式类生成
      return `
        status-base 
        status-${status} 
        ${status === 0 || status === 4 ? 'clickable' : 'non-clickable'}
      `;
    },

    handleStatusClick(row) {
      const status = row.productionStatus;
      if (status === 0) {
        this.openDispatchDialog(row);
      } else if (status === 4) {
        // 修复：给正确的变量赋值 viewOrderCode
        this.viewOrderCode = row.orderCode;
        this.viewDispatchVisible = true;
      } else {
        this.$message({
          message: `当前状态：${this.getStatusText(status)}，不可操作`,
          type: 'info',
          duration: 1500
        });
      }
    },

    openDispatchDialog(row) {
      if (row.productionStatus !== 0) {
        this.$modal.msgWarning(`当前状态：${this.getStatusText(row.productionStatus)}，仅“未派单”可操作`);
        return;
      }
      this.selectedOrderCode = row.orderCode;
      this.dispatchVisible = true;
    },

    getFileName(url) {
      return url.substring(url.lastIndexOf('/') + 1);
    },

    getRooms() {
      findAllRoomsinformation().then((response) => {
        this.rooms = response.data;
        this.formattedRooms = this.rooms.map(room => ({
          roomName: room.roomName,
          roomCode: room.roomCode
        }));
      });
    },

    getRoomNameById(roomCode) {
      const room = this.rooms.find((r) => r.roomCode === roomCode);
      return room ? room.roomName : roomCode;
    },

    showMaterialSelectDialog() {
      const materialDialog = this.$refs.materialSelectDialog;
      materialDialog.materialCode = this.form.productionMaterialCode || "";
      materialDialog.show();
    },

    handleMaterialSelected(materials) {
      this.form.productionMaterialCode = materials
        .map(m => m.materialCode)
        .join(", ");
    },

    dialogClosed() { },

    getList() {
      this.loading = true
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    cancel() {
      this.open = false
      this.reset()
    },

    reset() {
      this.form = {
        id: null,
        orderCode: null,
        orderName: null,
        gmpIndustry: null,
        productName: null,
        productCode: null,
        productionMaterialCode: null,
        spec: null,
        plannedOutput: null,
        roomCode: null,
        approver: null,
        approveDate: null,
        contentUrl: null,
        remark: null,
        orderStatus: null,
        productionStatus: null,
        workOrderCode: null,
        createTime: null,
        updateTime: null,
        isDelete: null
      }
      this.resetForm("form")
    },

    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改生产指令"
      })
    },

    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    handleExport() {
      this.download('product/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.material-info {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-top: 10px;
}

.custom-order-page {
  padding: 20px;
  background-color: #f9fafc;
  overflow-y: auto;
}

.custom-input,
.custom-select,
.custom-date-picker {
  width: 100%;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.custom-input:hover,
.custom-select:hover,
.custom-date-picker:hover {
  border-color: #409eff;
}

.custom-btn {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.custom-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
}

.custom-pagination {
  margin-top: 16px;
  text-align: right;
}

.custom-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.custom-dialog-form {
  max-height: 700px;
  max-width: 1500px;
  overflow-y: auto;
  overflow-x: hidden;
}

.custom-material-info {
  margin-top: 8px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.custom-file-upload,
.custom-editor {
  width: 100%;
  border-radius: 4px;
}

.custom-dialog-footer {
  text-align: right;
}

.download-link {
  display: inline-flex;
  align-items: center;
  color: #409eff;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s;
  text-decoration: none;
}

.download-link:hover {
  color: #66b1ff;
  background-color: #ecf5ff;
}

.no-file {
  color: #909399;
  font-size: 12px;
}

.production-status-btn {
  display: inline-flex;
  align-items: center;
  padding: 5px 12px;
  border-radius: 6px;
  font-size: 13px;
  transition: all 0.25s ease;
  border: 1px solid transparent;
}

.status-icon {
  margin-right: 6px;
  font-size: 14px;
}

.status-text {
  font-weight: 500;
}

.action-hint {
  margin-left: 8px;
  font-size: 12px;
  display: inline-flex;
  align-items: center;
}

.clickable {
  cursor: pointer;
}

.clickable:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
}

.non-clickable {
  cursor: default;
  opacity: 0.9;
}

.status-base.status-0 {
  background-color: #f0f7ff;
  border-color: #bed6ff;
  color: #165dff;
}

.status-base.status-0:hover {
  background-color: #e6f0ff;
}

.status-base.status-1 {
  background-color: #f0f7ff;
  border-color: #d9e8ff;
  color: #4096ff;
}

.status-base.status-2 {
  background-color: #f6ffed;
  border-color: #d9f7be;
  color: #52c41a;
}

.status-base.status-3 {
  background-color: #f6ffed;
  border-color: #b7eb8f;
  color: #237804;
}

.status-base.status-4 {
  background-color: #fff2e8;
  border-color: #ffd8bf;
  color: #fa541c;
}
</style>